package org.reserved.util;

import org.apache.commons.lang.StringUtils;
import org.reserved.loadbalance.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenxuning
 * @date 2022/10/08  10:54
 */
@Component
public class LoggerUtil {
    /**
     * type-0只打印日志 type-1打印日志且发送钉钉消息
     */
    private int type = 0;

    private Logger logger = LoggerFactory.getLogger(LoggerUtil.class);

    private ConcurrentHashMap<String, Date> messageMap = new ConcurrentHashMap(15);

    @Autowired
    private DingTalkUtil dingTalkUtil;

    public LoggerUtil(PropertyUtil propertiesPojo) {
        if (StringUtils.isNotEmpty(propertiesPojo.getDingSecret()) && StringUtils.isNotEmpty(propertiesPojo.getDingAccessToken())) {
            type = 1;
        }
    }

    public void info(String content, String argument) {
        logger.info(content, argument);
    }

    public void error(String content, String argument) {
        logger.error(content, argument);
        this.dingTalk(content, argument);
    }

    public void dingTalk(String content, String argument) {
        if (type == 1) {
            String text;
            if (argument != null) {
                text = content.replace("{}", argument);
            } else {
                text = content;
            }

            Date tipTime = messageMap.get(text);
            if (tipTime == null || System.currentTimeMillis() - tipTime.getTime() > 60 * 10 * 1000) {
                synchronized (LoggerUtil.class) {
                    tipTime = messageMap.get(text);
                    if (tipTime == null || System.currentTimeMillis() - tipTime.getTime() > 60 * 10 * 1000) {
                        messageMap.put(text, new Date());
                        dingTalkUtil.sendText(text);
                    }
                }
            }
        }
    }
}
